<template>
  <div class="app-container">
    <el-form ref="ruleForm" v-loading="listLoading" :model="product" element-loading-text="Loading" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-tabs type="border-card" class="table_style">
        <el-tab-pane label="通用信息">
          <el-form-item label="所属分类" prop="category_id">
            <el-select v-model="product.categoryId" filterable placeholder="请选择分类" style="width: 400px">
              <el-option-group
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
              >
                <el-option
                  v-for="child in category.children"
                  :key="child.id"
                  :label="child.name"
                  :value="child.id"
                />
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item label="选择标签">
            <el-select v-model="product.tags" multiple filterable placeholder="请选择标签" style="width: 400px" :multiple-limit="2">
              <el-option
                v-for="tag in tagList"
                :key="tag.id"
                :label="tag.name"
                :value="tag.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择品牌">
            <el-select v-model="product.brandId" filterable placeholder="请选择品牌" style="width: 400px">
              <el-option
                v-for="brand in brands"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="product.name" />
          </el-form-item>

          <el-form-item label="商品单价" prop="price">
            <el-input v-model="product.price" type="number" />
          </el-form-item>

          <el-form-item label="商品库存" prop="stock">
            <el-input v-model="product.stock" />
          </el-form-item>

          <el-form-item label="缩略图" prop="image">
            <el-upload
              class="avatar-uploader"
              :data="qiniuForm"
              :before-upload="beforeUpload"
              :on-success="uploadSuccess"
              action="https://upload.qiniup.com"
            >
              <img v-if="product.image" :src="product.image" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>

          <el-form-item label="描述信息" prop="desc">
            <el-input v-model="product.desc" type="textarea" rows="3" />
          </el-form-item>

          <el-form-item label="是否上架">
            <el-radio-group v-model="product.onsale" size="medium">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="商品属性">
            <el-checkbox-button v-model="product.recommend" size="medium">推荐药品</el-checkbox-button>
            <el-checkbox-button v-model="product.discount" size="medium">特惠药品</el-checkbox-button>
            <el-checkbox-button v-model="product.emergency" size="medium">应急储备</el-checkbox-button>
            <el-checkbox-button v-model="product.nourishing" size="medium">营养滋补</el-checkbox-button>
            <el-checkbox-button v-model="product.prevention" size="medium">防疫专区</el-checkbox-button>
            <el-checkbox-button v-model="product.commonUse" size="medium">家中常备</el-checkbox-button>
            <el-checkbox-button v-model="product.cardiovascular" size="medium">心脑血管</el-checkbox-button>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="详细信息" prop="content">
          <el-form-item label="商品规格" prop="specs">
            <el-input v-model="product.specs" />
          </el-form-item>

          <el-form-item label="计价单位" prop="unit">
            <el-input v-model="product.unit" />
          </el-form-item>

          <el-form-item label="批准文号" prop="approval_number">
            <el-input v-model="product.approval_number" />
          </el-form-item>
          <el-form-item label="生产厂家" prop="factory">
            <el-input v-model="product.factory" />
          </el-form-item>

          <el-form-item label="商标" prop="trademark">
            <el-input v-model="product.trademark" />
          </el-form-item>

          <el-form-item label="产地" prop="place_of_origin">
            <el-input v-model="product.place_of_origin" />
          </el-form-item>

          <el-form-item label="类别" prop="classification">
            <el-input v-model="product.classification" />
          </el-form-item>
          <el-form-item label="剂型" prop="drug">
            <el-input v-model="product.drug" />
          </el-form-item>

          <el-form-item label="有效期" prop="expiry_date">
            <el-input v-model="product.expiry_date" placeholder="有效期天数" />
          </el-form-item>

          <el-form-item label="温馨提示" prop="reminder">
            <el-input v-model="product.reminder" type="textarea" rows="3" />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品相册">
          <el-form-item>
            <el-upload
              class="upload-demo"
              drag
              action="https://upload.qiniup.com"
              multiple
              :data="qiniuForm"
              list-type="picture"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :on-success="handleGallerySuccess"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                可选择多张图片，<em>点击上传</em>
              </div>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <el-form-item class="sub_bottom">
        <el-button @click="resetForm('ruleForm')">返回首页</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid'
import { fetchCategoryList } from '@/api/category'
import { fetchBrandList } from '@/api/brand'
import { fetchTagList } from '@/api/tag'
import { createProduct } from '@/api/product'
import { fetchUpload } from '@/api/upload'

export default {
  data() {
    return {
      categories: [],
      brands: [],
      tagList: [],
      listLoading: true,
      qiniuForm: {
        key: '', // 文件名称
        token: ''
      },
      product: {
        categoryId: '',
        brandId: '',
        tags: [],
        name: '',
        price: '',
        stock: '',
        image: '',
        sale: 0,
        onsale: 1,
        recommend: 0,
        discount: 0,
        emergency: 0,
        nourishing: 0,
        prevention: 0,
        commonUse: 0,
        cardiovascular: 0,
        desc: '',
        specs: '',
        unit: '',
        approval_number: '',
        factory: '',
        trademark: '',
        place_of_origin: '',
        classification: '',
        drug: '',
        expiry_date: '',
        reminder: '',
        imgs: []
      },
      rules: {
        categoryId: [
          {
            required: true,
            message: '请选择商品分类',
            trigger: 'change'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 25,
            message: '长度在 3 到 25 个字符',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入商品单价',
            trigger: 'blur'
          }
        ],
        stock: [
          {
            required: true,
            message: '请输入商品库存',
            trigger: 'blur'
          }
        ],
        image: [
          {
            required: true,
            message: '请上传缩略图',
            trigger: 'blur'
          }
        ],
        desc: [
          {
            required: true,
            message: '请填写商品描述',
            trigger: 'blur'
          }
        ],
        specs: [
          {
            required: true,
            message: '请输入商品规格',
            trigger: 'blur'
          }
        ],
        unit: [
          {
            required: true,
            message: '请输入计量单位',
            trigger: 'blur'
          }
        ],
        approval_number: [
          {
            required: true,
            message: '请输入批准文号',
            trigger: 'blur'
          }
        ],
        factory: [
          {
            required: true,
            message: '请输入生产厂家',
            trigger: 'blur'
          }
        ],
        trademark: [
          {
            required: true,
            message: '请填写商标',
            trigger: 'blur'
          }
        ],
        place_of_origin: [
          {
            required: true,
            message: '请填写产地',
            trigger: 'blur'
          }
        ],
        classification: [
          {
            required: true,
            message: '请输入类别',
            trigger: 'blur'
          }
        ],
        drug: [
          {
            required: true,
            message: '请输入剂型',
            trigger: 'blur'
          }
        ],
        expiry_date: [
          {
            required: true,
            message: '请填写有效天数',
            trigger: 'blur'
          }
        ],
        reminder: [
          {
            required: true,
            message: '请填写温馨提示',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    // 所有分类
    fetchCategoryList().then((res) => {
      this.listLoading = true
      this.categories = res.data.categories
      this.listLoading = false
    })
    // 所有品牌
    fetchBrandList().then((res) => {
      this.listLoading = true
      this.brands = res.data.brands
      this.listLoading = false
    })
    // 所有标签
    fetchTagList('admin/tags').then((res) => {
      this.listLoading = true
      this.tagList = res.data.tags
      this.listLoading = false
    })
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) return
        createProduct(this.product).then((res) => {
          this.$message({
            message: res.message,
            type: 'success'
          })
          this.$router.push({ name: 'Product' })
        })
      })
    },
    resetForm(formName) {
      this.$router.push({ name: 'Product' })
    },
    // 上传之前(单图和多图)
    async beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      // 如果验证失败，返回假
      if (isJPG && isLt2M === false) return false

      // 如果验证成功，获取token
      const fileType = file.type === 'image/jpeg' ? 'jpg' : 'png' // 获取扩展名
      const res = await fetchUpload()
      this.qiniuForm = {
        key: `${uuidv4()}.${fileType}`, // 文件名称
        token: res.data.uploadToken
      }
      return true
    },
    // 上传成功，获取图片地址
    uploadSuccess(res) {
      this.product.image = 'https://image.holyzq.com/' + res.key
    },
    // 上传多图==移除图片
    handleRemove(file, fileList) {
    },
    // 上传多图 == 上传成功后
    handleGallerySuccess(response) {
      this.product.imgs.push('https://image.holyzq.com/' + response.key.split(', '))
    }
  }
}
</script>

<style scoped>
.sub_bottom {
  margin-top: 20px;
  margin-left: -100px;
}

.avatar-uploader {
  width: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-form-item__content {
  line-height: 0!important;
}

.el-upload--picture {
  width: 700px !important;
}
</style>
